<template>
  <div class="main-container">
    <!-- 顶部导航栏 -->
    <AppHeader 
      :currentView="currentView" 
      @navigate="handleNavigation"
      @languageChange="handleLanguageChange"
    />

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 小说世界主页视图 -->
      <NovelsView 
        v-if="currentView === 'novels'"
        :novels="novels"
        @selectNovel="selectNovel"
      />

      <!-- 小说详情视图（角色选择 + 对话） -->
      <NovelDetailView
        v-if="currentView === 'novel-detail'"
        :selectedNovel="selectedNovel"
        :selectedCharacter="selectedCharacter"
        :messages="messages"
        :isThinking="isThinking"
        :inputMessage="inputMessage"
        :username="userStore.currentUser?.username"
        @backToNovels="backToNovels"
        @showCharacterModal="showCharacterModal"
        @toggleCharacterFavorite="toggleCharacterFavorite"
        @clearMessages="clearMessages"
        @exportChat="exportChat"
        @playAudio="playAudio"
        @likeMessage="likeMessage"
        @updateInput="updateInput"
        @insertEmoji="insertEmoji"
        @uploadFile="uploadFile"
        @sendMessage="sendMessage"
      />

      <!-- 个人中心视图 -->
      <ProfileView
        v-if="currentView === 'profile'"
        :username="userStore.currentUser?.username"
        :userProfile="userStore.userProfile"
        :stats="userStats"
        :settings="userSettings"
        @updateSetting="updateUserSetting"
      />
    </main>

    <!-- 语音控制器 -->
    <VoiceController />

    <!-- 角色介绍弹窗 -->
    <CharacterModal
      :show="showModal"
      :character="selectedModalCharacter"
      :novelTitle="selectedNovel?.title"
      @close="closeModal"
      @startChat="confirmStartChat"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/modules/user'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入组件
import AppHeader from '../components/common/AppHeader.vue'
import NovelsView from '../components/novel/NovelsView.vue'
import NovelDetailView from '../components/novel/NovelDetailView.vue'
import ProfileView from '../components/user/ProfileView.vue'
import CharacterModal from '../components/novel/CharacterModal.vue'
import VoiceController from '../components/chat/VoiceController.vue'

// 导入类型和API
import type { Novel, Character, LegacyCharacter, Message, UserStats } from '../types/novel'
import { novelApi } from '../services/api'
import { setLocale, getCurrentLocale, type SupportedLocale } from '../i18n'

// 导入API
import { chatApi } from '../api/index'

// 在script setup中添加session管理
const currentSessionId = ref<number | null>(
  localStorage.getItem('currentSessionId') ? 
  parseInt(localStorage.getItem('currentSessionId')!) : 
  null
)

// 基础状态
const router = useRouter()
const userStore = useUserStore()
const { t } = useI18n()

const currentView = ref('novels')
const selectedNovel = ref<Novel | null>(null)
const selectedCharacter = ref<Character | LegacyCharacter | null>(null)
const inputMessage = ref('')
const isThinking = ref(false)

// 弹窗相关
const showModal = ref(false)
const selectedModalCharacter = ref<Character | LegacyCharacter | null>(null)

// 用户统计数据
const userStats = ref({
  totalChats: 0,
  todayChats: 0,
  favoriteCharacters: 0,
  usageDays: 0,
  mostUsedCharacter: '',
  mostUsedNovel: ''
})

// 用户设置
const userSettings = ref({
  speechSpeed: 1.0,
  autoPlay: false,
  emotionLevel: 80,
  replyLength: 'medium',
  language: 'zh-CN',
  theme: 'auto',
  themeColor: 'blue'
})

const STATS_KEY = 'echo_role_user_stats'
const FIRST_LOGIN_KEY = 'echo_role_first_login'

// 小说数据 - 从API获取
const novels = ref<Novel[]>([])
const isLoading = ref(false)

const messages = ref<Message[]>([])

// 计算属性
const favoriteCharacters = computed(() => {
  const allCharacters: (Character | LegacyCharacter)[] = []
  novels.value.forEach((novel: Novel) => {
    if (novel.characters) {
    allCharacters.push(...novel.characters)
    }
  })
  return allCharacters.filter((char: Character | LegacyCharacter) => char.favorited)
})

// 监听sessionId变化，自动保存到localStorage
watch(currentSessionId, (newSessionId: number | null) => {
  if (newSessionId !== null) {
    localStorage.setItem('currentSessionId', newSessionId.toString())
  } else {
    localStorage.removeItem('currentSessionId')
  }
}, { immediate: false })

// 监听当前视图变化，保存到localStorage
watch(currentView, (newView: string) => {
  localStorage.setItem('mainCurrentView', newView)
}, { immediate: false })

// 监听选中的小说变化，保存到localStorage
watch(selectedNovel, (newNovel: Novel | null) => {
  if (newNovel) {
    localStorage.setItem('mainSelectedNovelId', newNovel.id.toString())
  } else {
    localStorage.removeItem('mainSelectedNovelId')
  }
}, { immediate: false })

// 监听选中的角色变化，保存到localStorage
watch(selectedCharacter, (newCharacter: Character | LegacyCharacter | null) => {
  if (newCharacter) {
    localStorage.setItem('mainSelectedCharacterId', newCharacter.id.toString())
  } else {
    localStorage.removeItem('mainSelectedCharacterId')
  }
}, { immediate: false })

// 方法
const handleNavigation = async (view: string) => {
  currentView.value = view
  
  if (view === 'profile' && !userStore.userProfile) {
    try {
      await userStore.fetchUserProfile()
    } catch (error) {
      console.error('加载用户资料失败:', error)
    }
  }
}

// 语言切换处理函数
const handleLanguageChange = (locale: SupportedLocale) => {
  console.log('[Main] Handling language change:', locale)
  setLocale(locale)
  
  // 更新用户设置中的语言
  userSettings.value.language = locale
  localStorage.setItem('echo_role_user_settings', JSON.stringify(userSettings.value))
  
  ElMessage.success(t('common.languageChanged'))
}

const selectNovel = (novel: Novel) => {
  selectedNovel.value = novel
  currentView.value = 'novel-detail'
}

const backToNovels = () => {
  currentView.value = 'novels'
  selectedNovel.value = null
  selectedCharacter.value = null
  messages.value = []
}

const showCharacterModal = (character: Character | LegacyCharacter) => {
  selectedModalCharacter.value = character
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
  setTimeout(() => {
    selectedModalCharacter.value = null
  }, 300)
}

const confirmStartChat = () => {
  if (selectedModalCharacter.value) {
    selectCharacterAndStartChat(selectedModalCharacter.value)
    closeModal()
  }
}

const selectCharacterAndStartChat = (character: Character | LegacyCharacter) => {
  selectedCharacter.value = character
  messages.value = []
  currentSessionId.value = null  // 重置会话ID
  
  // 更新角色使用统计
  const novelTitle = selectedNovel.value?.title || '未知'
  updateCharacterUsage(character.name, novelTitle)
  
  // 添加欢迎消息
  const welcomeMessage: Message = {
    id: Date.now(),
    type: 'character',
    name: character.name,
    content: getWelcomeMessage(character),
    timestamp: new Date(),
    likes: 0
  }
  
  messages.value.push(welcomeMessage)
  nextTick(() => scrollToBottom())
}

const getWelcomeMessage = (character: Character | LegacyCharacter) => {
  const welcomeMessages: Record<string, string> = {
    '张小敬': '你好！我是张小敬，长安的不良帅。有什么关于长安城的事情需要了解吗？',
    '李泌': '欢迎来到靖安司，我是李泌。有什么疑问可以向我咨询。',
    '龙波': '你好，我是龙波。虽然话不多，但有需要帮助的地方尽管说。',
    '唐三': '你好！我是唐三，很高兴认识你。有什么想了解斗罗大陆的事情吗？',
    '小舞': '哇！又有新朋友了！我是小舞，请多多指教哦～',
    '大师': '你好，我是玉小刚，大家都叫我大师。有什么武魂方面的问题可以问我。',
    '萧炎': '哈哈，又来了一个朋友！我是萧炎，三十年河东三十年河西，莫欺少年穷！',
    '萧薰儿': '萧炎哥哥经常提到要结交更多朋友呢，你好，我是薰儿。',
    '药尘': '年轻人，我是药尘。有什么关于炼药的问题可以向我请教。'
  }
  
  return welcomeMessages[character.name] || `你好！我是${character.name}，很高兴认识你！`
}

const toggleCharacterFavorite = (characterId: number) => {
  const stats = getUserStats()
  const character = findCharacterById(characterId)
  
  if (!character) return
  
  const index = stats.favoriteCharacterIds.indexOf(characterId)
  if (index > -1) {
    stats.favoriteCharacterIds.splice(index, 1)
    character.favorited = false
  } else {
    stats.favoriteCharacterIds.push(characterId)
    character.favorited = true
  }
  
  saveUserStats(stats)
  updateStatistics()
}

// 更新sendMessage函数
const sendMessage = async () => {
  if (!inputMessage.value.trim() || !selectedCharacter.value || isThinking.value) return
  
  const userMessage = {
    id: Date.now(),
    type: 'user' as const,
    name: userStore.currentUser?.username || '我',
    content: inputMessage.value,
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)
  const messageText = inputMessage.value
  inputMessage.value = ''
  
  // 更新对话次数统计
  updateTodayChats()
  
  await nextTick()
  scrollToBottom()
  
  // 调用真实的AI服务
  isThinking.value = true
  
  try {
    // 构建请求数据
    const requestData = {
      character_id: selectedCharacter.value.id,
      character_name: selectedCharacter.value.name,
      novel_project: getNovelProject(selectedNovel.value?.title || ''),
      novel_title: selectedNovel.value?.title || '',
      message: messageText,
      session_id: currentSessionId.value || undefined
    }
    
    // 调用后端API
    const response = await chatApi.sendMessage(requestData)
    
    // 调试：打印响应数据
    console.log('API 响应:', response)
    console.log('success 字段:', (response as any).success)
    
    if (response && (response as any).success) {
      // 更新会话ID
      if (!currentSessionId.value) {
        currentSessionId.value = (response as any).session.id
      }
      
      // 添加AI回复消息
      const botMessage = {
        id: Date.now() + 1,
        type: 'character' as const,
        name: selectedCharacter.value.name,
        content: (response as any).character_message.content,
        timestamp: new Date((response as any).character_message.created_at),
        likes: 0
      }
      
      messages.value.push(botMessage)
      
      // 自动播放语音
      if (userSettings.value.autoPlay) {
        await playAudio(botMessage)
      }
    } else {
      // AI调用失败，显示错误消息
      const errorMessage = {
        id: Date.now() + 1,
        type: 'character' as const,
        name: selectedCharacter.value.name,
        content: (response as any)?.character_message?.content || '抱歉，我现在无法回应，请稍后再试。',
        timestamp: new Date(),
        likes: 0
      }
      
      messages.value.push(errorMessage)
      ElMessage.error('AI服务暂时不可用，请稍后重试')
    }
    
  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 添加错误提示消息
    const errorMessage = {
      id: Date.now() + 1,
      type: 'character' as const,
      name: selectedCharacter.value.name,
      content: '抱歉，网络连接出现问题，请检查网络后重试。',
      timestamp: new Date(),
      likes: 0
    }
    
    messages.value.push(errorMessage)
    ElMessage.error('发送消息失败，请检查网络连接')
  } finally {
    isThinking.value = false
    await nextTick()
    scrollToBottom()
  }
}

const updateInput = (value: string) => {
  inputMessage.value = value
}

const clearMessages = async () => {
  try {
    await ElMessageBox.confirm(t('chat.clearConfirm'), t('chat.clearTitle'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
    
    messages.value = []
    if (selectedCharacter.value) {
      selectCharacterAndStartChat(selectedCharacter.value)
    }
    ElMessage.success(t('chat.cleared'))
  } catch (error) {
    // 用户取消操作
  }
}

const exportChat = () => {
  ElMessage.info(t('chat.exportInDev'))
}

const playAudio = async (message: Message) => {
  if (!selectedCharacter.value || !selectedNovel.value) {
    ElMessage.warning('请先选择角色和小说')
    return
  }

  try {
    const { useVoice } = await import('../services/voice')
    const { playMessage } = useVoice()
    
    const success = await playMessage(
      message.content,
      message.name,
      getNovelProject(selectedNovel.value.title),
      {
        autoPlay: true,
        roleType: message.type === 'character' ? 'protagonist' : 'supporting'
      }
    )
    
    if (success) {
      ElMessage.success('开始播放语音')
    } else {
      ElMessage.error('语音播放失败')
    }
  } catch (error) {
    console.error('语音播放失败:', error)
    ElMessage.error('语音服务暂时不可用')
  }
}

const likeMessage = (message: Message) => {
  message.likes = (message.likes || 0) + 1
  ElMessage.success(t('chat.liked'))
}

const insertEmoji = () => {
  // 表情插入逻辑现在在 ChatPanel 组件中处理
  // 这里保留函数以保持接口兼容性
}

const uploadFile = () => {
  // 文件上传逻辑现在在 ChatPanel 组件中处理
  // 这里保留函数以保持接口兼容性
}

const updateUserSetting = (key: string, value: any) => {
  ;(userSettings.value as any)[key] = value
  // 保存到localStorage
  localStorage.setItem('echo_role_user_settings', JSON.stringify(userSettings.value))
  
  // 应用主题设置
  if (key === 'theme' || key === 'themeColor') {
    applyThemeSettings()
  }
  
  // 应用语言设置
  if (key === 'language') {
    applyLanguageSettings(value)
  }
}

// 应用主题设置
const applyThemeSettings = () => {
  const theme = userSettings.value.theme
  const themeColor = userSettings.value.themeColor
  
  // 设置主题模式
  if (theme === 'dark') {
    document.documentElement.classList.add('dark')
  } else if (theme === 'light') {
    document.documentElement.classList.remove('dark')
  } else {
    // 自动模式，根据系统偏好设置
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    if (prefersDark) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 设置主题色彩
  document.documentElement.setAttribute('data-theme-color', themeColor)
}

// 应用语言设置
const applyLanguageSettings = (language: string) => {
  document.documentElement.setAttribute('lang', language)
  // 这里可以集成i18n国际化库
  console.log('Language changed to:', language)
}

// 从localStorage加载用户设置
const loadUserSettings = () => {
  const saved = localStorage.getItem('echo_role_user_settings')
  if (saved) {
    try {
      const settings = JSON.parse(saved)
      userSettings.value = { ...userSettings.value, ...settings }
    } catch (error) {
      console.error('Failed to load user settings:', error)
    }
  }
}

const scrollToBottom = () => {
  // 在实际的聊天面板中滚动到底部的逻辑会在ChatPanel组件中处理
}

// 统计数据管理函数（简化版本）
const getUserStats = (): UserStats => {
  const defaultStats: UserStats = {
    totalChats: 0,
    todayChats: 0,
    characterUsage: {},
    novelUsage: {},
    favoriteCharacterIds: [],
    lastLoginDate: new Date().toDateString(),
    firstLoginDate: new Date().toDateString()
  }
  
  const stored = localStorage.getItem(STATS_KEY)
  if (!stored) {
    return defaultStats
  }
  
  try {
    return { ...defaultStats, ...JSON.parse(stored) }
  } catch {
    return defaultStats
  }
}

const saveUserStats = (stats: UserStats) => {
  localStorage.setItem(STATS_KEY, JSON.stringify(stats))
}

const updateTodayChats = () => {
  const stats = getUserStats()
  const today = new Date().toDateString()
  
  // 如果是新的一天，重置今日对话数
  if (stats.lastLoginDate !== today) {
    stats.todayChats = 0
    stats.lastLoginDate = today
  }
  
  stats.todayChats += 1
  stats.totalChats += 1
  
  saveUserStats(stats)
  updateStatistics()
}

const updateCharacterUsage = (characterName: string, novelTitle: string) => {
  const stats = getUserStats()
  
  // 更新角色使用次数
  stats.characterUsage[characterName] = (stats.characterUsage[characterName] || 0) + 1
  
  // 更新小说使用次数
  stats.novelUsage[novelTitle] = (stats.novelUsage[novelTitle] || 0) + 1
  
  saveUserStats(stats)
  updateStatistics()
}

const findCharacterById = (id: number): Character | LegacyCharacter | null => {
  for (const novel of novels.value) {
    if (novel.characters) {
      const character = novel.characters.find((char: Character | LegacyCharacter) => char.id === id)
      if (character) return character
    }
  }
  return null
}

const calculateUsageDays = (): number => {
  const firstLogin = localStorage.getItem(FIRST_LOGIN_KEY)
  if (!firstLogin) {
    localStorage.setItem(FIRST_LOGIN_KEY, new Date().toDateString())
    return 1
  }
  
  const firstDate = new Date(firstLogin)
  const today = new Date()
  const diffTime = Math.abs(today.getTime() - firstDate.getTime())
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return Math.max(1, diffDays)
}

const updateStatistics = () => {
  const stats = getUserStats()
  
  userStats.value.totalChats = stats.totalChats
  userStats.value.todayChats = stats.todayChats
  userStats.value.usageDays = calculateUsageDays()
  userStats.value.favoriteCharacters = favoriteCharacters.value.length
  
  // 计算最常用角色
  const mostUsedChar = Object.entries(stats.characterUsage)
    .sort(([,a], [,b]) => b - a)[0]
  userStats.value.mostUsedCharacter = mostUsedChar ? mostUsedChar[0] : '暂无'
  
  // 计算最爱小说
  const mostUsedNovelEntry = Object.entries(stats.novelUsage)
    .sort(([,a], [,b]) => b - a)[0]
  userStats.value.mostUsedNovel = mostUsedNovelEntry ? mostUsedNovelEntry[0] : '暂无'
  
  // 更新收藏状态
  stats.favoriteCharacterIds.forEach(id => {
    const character = findCharacterById(id)
    if (character) {
      character.favorited = true
    }
  })
}

// 从API获取小说数据
const loadNovels = async () => {
  try {
    isLoading.value = true
    const novelList = await novelApi.getNovelList()
    novels.value = novelList
  } catch (error) {
    console.error('Failed to load novels:', error)
    ElMessage.error('加载小说数据失败')
  } finally {
    isLoading.value = false
  }
}

onMounted(async () => {
  // 页面加载完成后的初始化
  await loadNovels()
  updateStatistics()
  
  // 加载用户设置
  loadUserSettings()
  applyThemeSettings()
  
  // 初始化语言设置
  const currentLang = getCurrentLocale() as SupportedLocale
  if (userSettings.value.language !== currentLang) {
    userSettings.value.language = currentLang
  }
  applyLanguageSettings(userSettings.value.language)
  
  if (userStore.isLoggedIn && !userStore.userProfile) {
    try {
      await userStore.fetchUserProfile()
    } catch (error) {
      console.error('加载用户资料失败:', error)
    }
  }
  
  if (!localStorage.getItem(FIRST_LOGIN_KEY)) {
    localStorage.setItem(FIRST_LOGIN_KEY, new Date().toDateString())
  }
  
  // 恢复Main页面状态
  restoreMainPageState()
  
  // 监听语言变化事件
  window.addEventListener('language-changed', handleLanguageChangedEvent as EventListener)
})

// 监听语言变化事件处理函数
const handleLanguageChangedEvent = (event: Event) => {
  const customEvent = event as CustomEvent
  const locale = customEvent.detail.locale
  userSettings.value.language = locale
  localStorage.setItem('echo_role_user_settings', JSON.stringify(userSettings.value))
}

onUnmounted(() => {
  window.removeEventListener('language-changed', handleLanguageChangedEvent as EventListener)
})

// 恢复Main页面状态
const restoreMainPageState = async () => {
  try {
    const savedState = localStorage.getItem('mainPageState')
    if (savedState) {
      const state = JSON.parse(savedState)
      
      // 恢复当前视图
      if (state.currentView) {
        currentView.value = state.currentView
      }
      
      // 恢复选中的小说
      if (state.selectedNovelId && novels.value.length > 0) {
        const novel = novels.value.find(n => n.id.toString() === state.selectedNovelId)
        if (novel) {
          selectedNovel.value = novel
          
          // 恢复选中的角色
          if (state.selectedCharacterId && novel.characters) {
            const character = novel.characters.find(c => c.id.toString() === state.selectedCharacterId)
            if (character) {
              selectedCharacter.value = character
            }
          }
        }
      }
      
      // 清除保存的状态，避免重复恢复
      localStorage.removeItem('mainPageState')
    }
  } catch (error) {
    console.error('恢复Main页面状态失败:', error)
  }
}

// 添加获取小说项目的辅助函数
const getNovelProject = (novelTitle: string): string => {
  if (novelTitle.includes('斗罗大陆')) return 'douluo_dalu'
  if (novelTitle.includes('斗破苍穹')) return 'doupo_cangqiong'
  if (novelTitle.includes('长安十二时辰')) return 'changan_twelve'
  return 'douluo_dalu' // 默认值
}
</script>

<style scoped>
.main-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.main-content {
  flex: 1;
  overflow-y: auto;
}
</style> 